# @Author：silence
# @Email：792245022@qq.com
# @Date：2025/3/3 23:35

import urllib.request


def creat_request(page: int):
    url = f"https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&start={(page - 1) * 20}&limit=20"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36"
    }

    return urllib.request.Request(url=url, headers=headers)


def get_content(req: urllib.request.Request):
    response = urllib.request.urlopen(req)
    return response.read().decode("utf-8")


def download(content: str, page: int):
    path = f"douban-{page}.json"
    with open(path, "w", encoding="utf-8") as fw:
        fw.write(content)
    print(f"第{page}页爬取完成！")


if __name__ == "__main__":
    start_page = int(input("请输入开始爬取的页码："))
    end_page = int(input("请输入结束爬取的页码："))

    for page in range(start_page, end_page + 1):
        # 获取请求
        req = creat_request(page)
        # 获取响应的数据
        content = get_content(req)
        # 下载数据
        download(content, page)
